'use strict';

const { Controller } = require('egg');
const { Op } = require('sequelize');

class BaseController extends Controller {
  constructor(ctx, serviceName) {
    super(ctx);
    this.serviceName = serviceName;
  }
  async index() {
    const { query, service } = this.ctx;
    let { pageNum, pageSize } = query;
    let page = Number(pageNum) || 1;
    let size = Number(pageSize) || 10;
    delete query.pageNum
    delete query.pageSize
    const list = await service[this.serviceName].getPage(this.getPageQuery(query), page, size);
    this.ctx.success(list);
  }
  async create() {
    const { ctx } = this;
    const data = ctx.request.body;
    await ctx.service[this.serviceName].create(data);
    ctx.success(data, 200);
  }
  async update() {
    const { ctx } = this;
    const id = ctx.params.id;
    const infos = ctx.request.body;
    if (!id) throw new Error('必须传递ID参数');
    if (Object.keys(infos).length === 0) throw new Error('请传递修改的内容');
    await ctx.service[this.serviceName].update(id, infos);
    ctx.success(id, 200);
  }
  async destroy() {
    const uid = Number(this.ctx.params.id);
    if (!uid) throw new Error('ID 有误');
    await this.ctx.service[this.serviceName].deleteById(uid);
    this.ctx.success(uid); // 删除成功返回被删除的用户ID
  }
  async show() {
    const { params, service } = this.ctx;
    const findItem = await service[this.serviceName].findOne(params.id);
    this.ctx.success(findItem);
  }
  async allList() {
    const { service } = this.ctx;
    let where = this.getListQuery(this.ctx.query)
    const list = await service[this.serviceName].allList(where);
    this.ctx.success(list);
  }
  getPageQuery(query) {
    const where = {};
    for (const queryKey in query) {
      if (query[queryKey]) {
        if (queryKey.includes('_id')) {
          where[queryKey] = query[queryKey];
        } else {
          where[queryKey] = {
            [Op.like]: `%${query[queryKey]}%`,
          }
        }
      }
    }
    return where;
  }
  getListQuery(query) {
    const where = {};
    for (const queryKey in query) {
      if (query[queryKey]) {
        if (queryKey.includes('_id')) {
          where[queryKey] = query[queryKey];
        } else {
          where[queryKey] = {
            [Op.like]: `%${query[queryKey]}%`,
          }
        }
      }
    }
    return where;
  }
}

module.exports = BaseController;
